package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
@Autowired
private EmpExprService empExprService;

    //添加事务管理,确保同时成功同时失败
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        //保存员工
        this.save(emp);
        //获取员工工作经历
        List<EmpExpr> exprList = emp.getExprList();

        if (exprList!=null && exprList.size()>0){
            //给工作经历设置员工id
            exprList.forEach(exList->exList.setEmpId(emp.getId()));
            boolean result = empExprService.saveBatch(exprList);
            return result;
        }
        return false;
    }

    @Override
    public Emp getEmpById(Integer id) {
        //拿到员工数据
        Emp emp = this.getById(id);
        emp.setUpdateTime(LocalDateTime.now());
        //拿员工的工作经历
        //需要根据id条件 select * from emp_expr where emp_id =?
        LambdaQueryWrapper<EmpExpr> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EmpExpr::getEmpId,emp.getId());
        List<EmpExpr> list = empExprService.list(lqw);
        emp.setExprList(list);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEmpById(Emp emp) {
        //先拿到员工的工作经历
        List<EmpExpr> exprList = emp.getExprList();
        //查询是否有此员工
        Emp empById = this.getEmpById(emp.getId());



        LambdaQueryWrapper<EmpExpr> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EmpExpr::getEmpId,emp.getId());
        //删除所有工作经历
        //delete from emp_expr where emp_id = ?
        if (empById!=null){
            //修改员工的数据
            this.updateById(emp);
            //删除所有工作经历
            empExprService.remove(lqw);
            //给工作经历设置id
            exprList.forEach(e->e.setEmpId(emp.getId()));
            boolean result = empExprService.saveBatch(exprList);
            return result;
        }
        return false;
    }

    @Override
    @Transactional
    public void removeEmpByIds(List<Integer> ids) {
        //先删除员工
        this.removeByIds(ids);
        //删除员工的工作经历
        //delete from emp_expr where emp_id in?
        LambdaQueryWrapper<EmpExpr> lqw = new LambdaQueryWrapper<>();
        lqw.in(EmpExpr::getEmpId,ids);
        empExprService.remove(lqw);
    }
}
